<template>
  <a-layout style="background-color: #efefef; height: 100%">
    <a-layout-sider
      :style="{
        overflow: 'auto',
        height: '100vh',
        position: 'fixed',
        left: 0,
        top: 0,
        bottom: 0,
      }"
    >
      <div class="ToolBarDark" style="color: white">
        <h1 style="text-align: center">VisitDD</h1>
        <a-avatar size="small" style="margin-right: 2px">
          <template #icon>
            <UserOutlined />
          </template>
        </a-avatar>
        <label>{{ userName }}</label>
      </div>
      <a-menu
        v-model:selectedKeys="selectedKeys"
        mode="inline"
        theme="dark"
        @click="onMenuClick"
        :items="items"
        :openKeys="state.openKeys"
      >
      </a-menu>
      <div
        style="position: absolute; bottom: 0; width: 100%"
        class="ToolBarBottomDark"
      >
        <a-badge :count="state.newMessageCount">
          <a-button
            type="link"
            :icon="h(MailOutlined)"
            :title="$t('422')"
            @click="goMyMessage"
          ></a-button>
        </a-badge>
        <a-button
          v-if="userRole == 'UrAdmin'"
          type="link"
          :icon="h(ControlFilled)"
          :title="$t('423')"
          @click="goAdmin"
        ></a-button>
        <a-button
          type="link"
          danger
          :icon="h(LogoutOutlined)"
          :title="$t('214')"
          @click="logout"
        ></a-button>
      </div>
    </a-layout-sider>
    <a-layout style="margin-left: 200px; background-color: white">
      <RouterView />
    </a-layout>
  </a-layout>
</template>
<script setup>
import { computed, h, onMounted, reactive } from "vue";
import CommonDefine from "@/component/CommonDefine";
import {
  ControlFilled,
  LogoutOutlined,
  MailOutlined,
  SettingOutlined,
  UserOutlined,
  QuestionCircleOutlined,
} from "@ant-design/icons-vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";

const { t } = useI18n();
const router = useRouter();
const appStore = CommonDefine.appStore();

function getItem(label, key, icon, children, type) {
  return {
    key,
    icon,
    children,
    label,
    type,
  };
}

const items = reactive([
  getItem(t("424"), "m1", () => h(SettingOutlined), [
    getItem(t("425"), "/index/my-model"),
    getItem(t("426"), "/index/my-query"),
    getItem("记录回收站", "/index/my-trash"),
  ]),
  getItem(t("427"), "m2", () => h(SettingOutlined), [
    getItem(t("428"), "/index/share-model"),
  ]),
  getItem(t("429"), "m3", () => h(SettingOutlined), [
    getItem(t("430"), "/index/my-log"),
    getItem(t("431"), "/index/event-log"),
  ]),
  getItem(t("432"), "m4", () => h(UserOutlined), [
    getItem(t("433"), "/index/profile"),
  ]),
]);

const selectedKeys = reactive(["/index/my-model"]);

const userName = computed(() => {
  return localStorage.getItem("uname");
});

const userRole = computed(() => {
  return localStorage.getItem("urole");
});

const state = reactive({
  visible: false,
  openKeys: ["m1", "m2", "m3", "m4"],
  newMessageCount: 0,
  popChat: false,
});

const onMenuClick = (event) => {
  let route = event.key;
  if (router.path != route) {
    //获取路由对象并切换
    router.push(route);
    selectedKeys.splice(0, selectedKeys.length);
    selectedKeys.push(route);
  }
};

const checkToken = () => {
  if (
    localStorage.getItem("token") != undefined &&
    localStorage.getItem("token") != "undefined" &&
    localStorage.getItem("token").length > 0
  ) {
    fetch("/api/v1/user/check-token", {
      method: "POST",
      headers: {
        Authorization: `Bearer ${localStorage.getItem("token")}`,
        "Content-Type": "application/json",
      },
    })
      .then((res) => res.json())
      .then((arm) => {
        if (arm.ok) {
          localStorage.setItem("token", arm.data);
          loadPubKey();
          loadLabelMaps();
          countNewMessage();
          router.push("/index/my-model");
        } else {
          router.push("/login");
        }
      })
      .catch(() => {
        router.push("/login");
      });
  } else {
    router.push("/login");
  }
};

const goMyMessage = () => {
  router.push("/index/my-message");
  state.newMessageCount = 0;
};

const logout = () => {
  localStorage.removeItem("token");
  localStorage.removeItem("llts");
  localStorage.removeItem("uid");
  localStorage.removeItem("uname");
  localStorage.removeItem("phone");
  router.push("/login");
};

const goAdmin = () => {
  if (userRole.value == "UrAdmin") {
    router.push("/admin");
  }
};

const loadPubKey = () => {
  CommonDefine.apiGetArm("/api/v1/pub-key", (d) => {
    appStore.pubKey = d;
  });
};

const countNewMessage = () => {
  CommonDefine.apiGetArm("/api/v1/user/new-message-count", (d) => {
    state.newMessageCount = d;
  });
};

const loadLabelMaps = () => {
  CommonDefine.apiGetArm("/api/v1/common/codes/FieldType", (d) => {
    appStore.aryFieldType = d;
  });
  CommonDefine.apiGetArm("/api/v1/common/codes/VisitGroupType", (d) => {
    appStore.aryVgt = d;
  });
  CommonDefine.apiGetArm("/api/v1/common/codes/VisitRight", (d) => {
    appStore.arySrmType = d;
  });
  CommonDefine.apiGetArm("/api/v1/common/codes/VisitRuleOfFields", (d) => {
    appStore.aryVisitLimitType = d;
  });
  CommonDefine.apiGetArm("/api/v1/common/codes/ComputeAction", (d) => {
    appStore.aryComputAction = d;
  });
  CommonDefine.apiGetArm("/api/v1/user/others", (d) => {
    appStore.otherUsers = d;
    appStore.otherUsers.forEach((item) => {
      item.key = item.id.toString();
    });
  });
  CommonDefine.apiGetArm("/api/v1/common/codes/FieldValueEvaluation", (d) => {
    appStore.aryFieldValueEvaluation = d;
  });
  CommonDefine.apiGetArm("/api/v1/common/codes/RecordValueRuleDetail", (d) => {
    appStore.aryRecordValueRuleDetail = d;
  });
};

onMounted(() => {
  checkToken();
});
</script>
